<script>
import { h } from 'vue';
import { useFullscreen } from '@vueuse/core';

import loadScript from '../../utils/loadScript.js';

export default {
  name: 'map-core-normal',
  emits: ['ready'],
  props: {
    mapOptions: { type: [Object, Function], default: () => ({}) },
  },
  data() {
    return {
      ready: false,
    };
  },
  computed: {
    containerStyle() {
      return { visibility: this.ready ? 'visible' : 'hidden' };
    },
  },
  async mounted() {
    await this.createMap();
    this.scope = {
      map: this.map,
      mapGetter: () => this.map,
    };
    this.ready = true;
    setTimeout(() => {
      this.$emit('ready', this.scope);
    }, 30);

    const fullscreen = useFullscreen();
    this.$watch(
      () => fullscreen.isFullscreen,
      () => {
        if (this.map) {
          let currentZoom = this.map.getZoom();
          this.map.setZoom(fullscreen.isFullscreen ? ++currentZoom : --currentZoom);
        }
      },
      { immediate: false }
    );
  },
  unmounted() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    async createMap() {
      //标准版后台index.html文件里面的地图引入取消掉了
      //在index.html中引入加载慢，会导致登录页面加载很久
      await loadScript('//webapi.amap.com/maps?v=1.4.15&key=d99cf0fc41f79425572e5b1298c0f21c');
      const option = Object.assign({}, typeof this.mapOptions === 'function' ? this.mapOptions() : this.mapOptions, {
        zooms: [3, 24], //传入的zooms不生效
        expandZoomRange: true,
        viewMode: '3D',
        layers: [
          new AMap.TileLayer(), // 写在mapOptions里面报错，项目里面还没有加载amap
          new AMap.Buildings({
            zIndex: 130,
            merge: false,
            sort: false,
            opacity: 1,
            zooms: [12, 20],
            //n倍于默认高度，3D下有效
            heightFactor: 5,
          }),
        ],
      });
      const container = this.$refs.containerRef;
      this.map = new AMap.Map(container, option);
      return new Promise((resolve) => {
        if (this.map.loaded) {
          // console.log('map.loaded: ', this.map.loaded, this.map);
          return resolve();
        }
        this.map.on('complete', resolve);
      });
    },
  },
  render() {
    return h('div', { class: 'map-core map-core-normal' }, [
      h('div', { ref: 'containerRef', class: 'map-container', style: this.containerStyle }),
      this.ready === true && this.$slots.default ? this.$slots.default(this.scope) : null,
    ]);
  },
};
</script>

<style lang="less">
.map-core {
  position: relative;
  width: 100%;
  height: 100%;
  .map-container {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: 0;
    overflow: hidden;
    transition: opacity ease 1s;
  }
  .amap-logo,
  .amap-copyright {
    display: none !important;
  }
}
</style>
